#include "g_local2.h"
#include <cassert>

static TargetableNode *_targetablesHead = NULL;

void Targetables_Add(edict_t *targetable)
{
	TargetableNode *node = new TargetableNode;

	node->Entity = targetable;
	node->Next = node->Prev = NULL;

	if (_targetablesHead == NULL)
		_targetablesHead = node;
	else
	{
		_targetablesHead->Prev = node;
		node->Next = _targetablesHead;
		_targetablesHead = node;
	}

	targetable->Targetable = node;
}

void Targetables_Remove(edict_t *targetable)
{
	TargetableNode *node = const_cast<TargetableNode*>(targetable->Targetable);

	if (node == NULL)
	{
		assert(0);
		return;
	}

	if (node->Prev != NULL)
	{
		node->Prev->Next = node->Next;
		node->Next->Prev = node->Prev;
	}
	else
	{
		_targetablesHead = node->Next;

		if (_targetablesHead != NULL)
			_targetablesHead->Prev = NULL;
	}

	targetable->Targetable = NULL;
	delete node;
}

const TargetableNode *Targetables_GetHead()
{
	return _targetablesHead;
}

const Party *Targetables_GetParty(const TargetableNode *node)
{
	if (node->Entity->client != NULL)
		return node->Entity->Character.Party;

	if (node->Entity->Monster.Owner == NULL)
		return NULL;

	return node->Entity->Monster.Owner->Party;
}